package com.newasia.server.common.strategy.dataConversion;

import com.newasia.server.common.dataSource.DynamicDataSourceContextHolder;
import lombok.extern.slf4j.Slf4j;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * @author LiChong
 * @description 监控点详情数据
 * @date 2020/5/25
 */

@Slf4j
public class MonitorDetialData implements DataInvoke {

    @Override
    public Object invoke(Object proxyObj, Method method, Object[] args) throws Throwable{
        String sid = args[0].toString();
        String dsid = "data1";
        if(sid.compareTo("808003002")>0){
            dsid = "data2";
        }
        changeDataSource(dsid,method);
        Object object = method.invoke(proxyObj,args);
        restoreDataSource(dsid,method);
        object.getClass().getMethod("setTemplate").invoke(object);
        return object;
    }

    public void changeDataSource(String dsId,Method method) throws Throwable {
        if (!DynamicDataSourceContextHolder.containsDataSource(dsId)) {
            log.error("数据源[{}]不存在，使用默认数据源 > {}", dsId, method.getName());
        }else {
            log.info("切换数据源 : {} > {}", dsId, method.getName());
            DynamicDataSourceContextHolder.setDataSourceType(dsId);
        }
    }

    public void restoreDataSource(String dsId,Method method) {
        log.info("将数据源 : {} 复原> {}", dsId, method.getName());
        DynamicDataSourceContextHolder.clearDataSourceType();
    }
}
